﻿Public Class ConfigureForm

	' controls the data object bindings to the grid (allows adding/deleting of rows)
	Private WithEvents DataBinding As BindingSource

	Dim jlist As JumpList
	Dim catlist As List(Of JumpListCustomCategory)
	Dim links As New List(Of LinkData)


#Region " settings "

	''' <summary>
	''' Gets the settings filename stored in the user's local app data
	''' </summary>
	''' <value></value>
	''' <returns></returns>
	''' <remarks></remarks>
	Public ReadOnly Property SettingsFile() As String
		Get
			Dim filename As String
			Dim filepath As String
			filepath = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), My.Application.Info.ProductName)
			filename = "links.xml"
			Return IO.Path.Combine(filepath, filename)
		End Get
	End Property

	''' <summary>
	''' load the settings file, if it exists
	''' </summary>
	''' <remarks></remarks>
	Private Sub LoadSettings()
		Dim filename As String = SettingsFile
		If IO.File.Exists(filename) Then
			Dim xs As New Xml.Serialization.XmlSerializer(GetType(List(Of LinkData)))
			links = CType(xs.Deserialize(New IO.FileStream(filename, IO.FileMode.Open)), Global.System.Collections.Generic.List(Of Global.Linx.LinkData))
		End If
	End Sub

	''' <summary>
	''' save the settings file
	''' </summary>
	''' <remarks></remarks>
	Friend Sub SaveSettings()
		Dim filename As String = SettingsFile
		Dim path As String = IO.Path.GetDirectoryName(filename)
		IO.Directory.CreateDirectory(path)
		Dim xs As New Xml.Serialization.XmlSerializer(GetType(List(Of LinkData)))
		xs.Serialize(New IO.FileStream(filename, IO.FileMode.Create), links)
	End Sub

#End Region


#Region " form and controls events "

	''' <summary>
	''' Front Entry
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub ConfigureForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

		Try

			' set the form icon
			Me.Icon = My.Resources.app_icon

			' show the license on first run
			If My.Settings.FirstRun Then
				Dim foo As New LicenseForm
				If foo.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
					My.Settings.FirstRun = False
					My.Settings.Save()
				Else
					Me.Close()
					Exit Sub
				End If
			End If

			' upgrade application settings
			If My.Settings.ShouldUpdate Then
				My.Settings.Upgrade()
				My.Settings.ShouldUpdate = False
				My.Settings.Save()
			End If

			' force create the window handle, which the jlist needs to instantiate :p
			lblVersion.Text = My.Application.Info.Version.ToString
			Me.MinimumSize = Me.Size
			Me.Show()

			' show the splash form
			'My.Forms.SplashForm.Show()

			' load link settings and create the jumplist
			LoadSettings()
			BuildJumplist(links)

			' pop the list
			Populate_LinkList()

			' set all link control tooltips to their tag/url
			For Each c As Control In tabAbout.Controls
				If TypeOf c Is LinkLabel Then
					ToolTip1.SetToolTip(c, CStr(c.Tag))
				End If
			Next

		Catch ex As Exception
			ErrorForm.Show(ex)
		End Try

	End Sub

	''' <summary>
	''' Cancel changes
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
		Me.DialogResult = Windows.Forms.DialogResult.Cancel
		Me.Close()
	End Sub

	''' <summary>
	''' save and apply settings
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
		Try
			SaveSettings()
			SetUIButtons(False)
			BuildJumplist(links)
			Me.DialogResult = Windows.Forms.DialogResult.OK
			Me.Close()
		Catch ex As Exception
			ErrorForm.Show(ex)
		End Try
	End Sub

#End Region

#Region " jumplist code "

	''' <summary>
	''' Build the jumplist
	''' </summary>
	''' <remarks>We use the Window API pack to use jumplists</remarks>
	Private Sub BuildJumplist(ByVal items As List(Of LinkData))

		Try

			catlist = New List(Of JumpListCustomCategory)
			jlist = JumpList.CreateJumpList

			For Each link As LinkData In (From l As LinkData In items Order By l.Category, l.Title).ToArray

				' create the link
				Dim jlink As New JumpListLink(link.Path, link.Title)
				jlink.Arguments = link.Arguments

				' if this is a directory
				If IO.Directory.Exists(link.Path) Then
					' use the explorer folder icon if this is a directory
					jlink.IconReference = New IconReference("explorer.exe", 1)
				Else

					' use the link target as the icon
					If link.AlternateIconRef.Length = 0 Then
						jlink.IconReference = New IconReference(link.Path, link.IconIndex)
					Else
						jlink.IconReference = New IconReference(link.AlternateIconRef, link.IconIndex)
					End If

					' set the working dir
					If link.WorkingDir.Length = 0 Then
						jlink.WorkingDirectory = IO.Path.GetDirectoryName(link.Path)
					Else
						jlink.WorkingDirectory = link.WorkingDir
					End If

				End If

				Dim iCanHazCategory As String = link.Category
				Dim catInTheHat As JumpListCustomCategory
				Dim possibleCats As List(Of JumpListCustomCategory)
				possibleCats = (From c In catlist Where c.Name = iCanHazCategory).ToList

				If possibleCats.Count = 0 Then
					catInTheHat = New JumpListCustomCategory(link.Category)
					catlist.Add(catInTheHat)
					jlist.AddCustomCategories(catInTheHat)
				Else
					catInTheHat = possibleCats(0)
				End If

				catInTheHat.AddJumpListItems(jlink)

			Next

			jlist.Refresh()

		Catch ex As Exception
			ErrorForm.Show(ex)
		End Try

	End Sub

	''' <summary>
	''' Update the given link item
	''' </summary>
	''' <param name="item"></param>
	''' <remarks></remarks>
	Friend Sub UpdateLinkItem(ByVal item As LinkData)
		links.Remove(item)
		links.Add(item)
		Populate_LinkList()
		SetUIButtons(True)
	End Sub

#End Region


#Region " listview and toolbar "

	''' <summary>
	''' Get a list of used categories
	''' </summary>
	''' <returns></returns>
	''' <remarks></remarks>
	Private Function GetCategoryList() As List(Of String)
		Dim items As New List(Of String)
		For Each item As ListViewItem In lvwLinks.Items
			If Not items.Contains(item.Group.Name) Then
				items.Add(item.Group.Name)
			End If
		Next
		Return items
	End Function

	''' <summary>
	''' Toggle the UI buttons for the given enable state
	''' </summary>
	''' <param name="enabled"></param>
	''' <remarks></remarks>
	Private Sub SetUIButtons(ByVal enabled As Boolean)
		btnSave.Enabled = enabled
	End Sub

	''' <summary>
	''' Edit a link item
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub lvwLinks_ItemActivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwLinks.ItemActivate
		Dim editor As New LinkEditForm
		editor.Categories = GetCategoryList()
		editor.LinkItem = CType(lvwLinks.SelectedItems(0).Tag, LinkData)
		editor.Owner = Me
		editor.Show()
	End Sub

	''' <summary>
	''' Toggle toolbar button states based on selected list item
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub lvwLinks_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvwLinks.SelectedIndexChanged
		tbnDeleteLink.Enabled = (lvwLinks.SelectedItems.Count = 1)
	End Sub

	''' <summary>
	''' populate the list
	''' </summary>
	''' <remarks></remarks>
	Private Sub Populate_LinkList()
		Try
			lvwLinks.Items.Clear()
			For Each link As LinkData In (From l As LinkData In links Order By l.Category, l.Title).ToArray

				' create the grouping
				Dim grp As ListViewGroup = lvwLinks.Groups(link.Category)
				If IsNothing(grp) Then
					grp = New ListViewGroup(link.Category, link.Category)
					lvwLinks.Groups.Add(grp)
				End If

				' create the item
				Dim item As New ListViewItem(link.Title)
				item.SubItems.Add(String.Format("{0} {1}", link.Path, link.Arguments))
				item.Tag = link
				item.Group = grp

				lvwLinks.Items.Add(item)

			Next

			' show the count of items
			lblStatus.Text = String.Format("{0} link{1}", lvwLinks.Items.Count, IIf(lvwLinks.Items.Count = 1, "", "s"))
			' resize the view to fit
			lvwLinks.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
			' focus the list
			lvwLinks.Focus()
			' switch to the about tab if there are no links defined
			If (links.Count = 0) Then TabControl1.SelectedTab = tabAbout

		Catch ex As Exception
			ErrorForm.Show(ex)
		Finally
			SetUIButtons(False)
		End Try
	End Sub

	''' <summary>
	''' Add a new link item
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub tbnAddLink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbnAddLink.Click
		Dim item As New LinkData
		Dim editor As New LinkEditForm
		editor.Categories = GetCategoryList()
		editor.LinkItem = item
		editor.Owner = Me
		editor.Show()
	End Sub

	''' <summary>
	''' Remove
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub tbnDeleteLink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbnDeleteLink.Click
		If lvwLinks.SelectedItems.Count = 1 Then
			links.Remove(CType(lvwLinks.SelectedItems(0).Tag, LinkData))
			lvwLinks.SelectedItems(0).Remove()
			SetUIButtons(True)
		End If
	End Sub

	''' <summary>
	''' Refresh the jumplist from the current listview items
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub btnRefreshJumplist_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefreshJumplist.Click
		Dim items As New List(Of LinkData)
		For Each item As ListViewItem In lvwLinks.Items
			items.Add(CType(item.Tag, LinkData))
		Next
		BuildJumplist(items)
	End Sub

#End Region

#Region " about tab "

	''' <summary>
	''' Show the license
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub btnLicense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLicense.Click
		My.Forms.LicenseForm.ShowDialog(Me)
	End Sub

	''' <summary>
	''' visit the home of Linx
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub btnWebsite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWebsite.Click
		Try
			Process.Start("http://code.google.com/p/linx-lists/")
		Catch ex As Exception
			ErrorForm.Show(ex)
		End Try
	End Sub

	''' <summary>
	''' show the gesture howto
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub lnkDragGesture_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkDragGesture.LinkClicked
		Dim foo As New HowtoForm
		foo.DefaultUIndex = 1
		foo.Show()
	End Sub

	''' <summary>
	''' show how to increase max list items
	''' </summary>
	''' <param name="sender"></param>
	''' <param name="e"></param>
	''' <remarks></remarks>
	Private Sub lnkIncreaseMaxItems_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkIncreaseMaxItems.LinkClicked
		Dim foo As New HowtoForm
		foo.DefaultUIndex = 3
		foo.Show()
	End Sub

#End Region

End Class